package com.example.campuslink.viewModel

import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.invitation.InvitationTable
import com.example.campuslink.commen.db.message.MessageTable
import com.example.campuslink.commen.db.school.SchoolInfoTable
import com.example.campuslink.commen.db.userInfo.UserInfoTable
import com.example.campuslink.commen.enums.MessageTypeEnum
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class PublicViewModel : BaseViewModel() {
    private val _topicList = MutableLiveData<String>("")
    val topicList = _topicList
    private val _userList = MutableLiveData<List<String>>()
    val userList = _userList
    var schoolInfo: SchoolInfoTable = SchoolInfoTable()
    var allImagePath = mutableListOf<String>()
    fun addTopic(topic: String) {
        if (_topicList.value?.split("\t")?.contains(topic)!! == false) {
            _topicList.value = (topicList.value ?: "") + "\t" + topic
        }

    }

    fun setTopic(topic: String) {
        _topicList.value = topic
    }

    fun getSchoolUserNumber() {
        val nowNumber: String = Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
        viewModelScope.launch(Dispatchers.IO) {
            val nowNumberInfo = userNumberDao.getUserNumber(nowNumber)
            schoolInfo = schoolInfoDao.getSchoolInfoBySchoolName(nowNumberInfo?.schoolName ?: "")
            _userList.postValue(schoolInfo.schoolUser.toList())
//            if (_userInfoList?.value?.size == 0) {
//                viewModelScope?.launch(Dispatchers.Main) {
//                    Toast.makeText(context, "该学校暂无其他用户!", Toast.LENGTH_SHORT).show()
//                }
//            }
        }
    }


    private val _userInfoList = MutableLiveData<List<UserInfoTable>>(listOf())
    val userInfoList = _userInfoList

    fun getUserList(number: String) {
        if (number.equals(Sp.getString(context, SpKey.USER_NUMBER.key, ""))) {
            return
        }
        val temp = _userInfoList.value?.toMutableList() ?: mutableListOf()
        temp.forEach {
            if (it.userNumber == number) {
                return
            }
        }
        viewModelScope.launch(Dispatchers.IO) {
            temp.add(userInfoDao.getUserInfoByUserNumber(number) ?: return@launch)
            _userInfoList.postValue(temp)
        }
    }

    private val _isShowUserList = MutableLiveData<Boolean>(false)
    val isShowUserList = _isShowUserList
    fun setIsShowUserList() {
        _isShowUserList.value = !(_isShowUserList.value ?: false)
    }

    private val _isShowCallUserNumber = MutableLiveData<String>("")
    val isShowCallUserNumber = _isShowCallUserNumber
    fun setIsShowCallUserNumber(userNumber: String) {
        _isShowCallUserNumber.value = userNumber
    }


    fun publicInvitation(title: String, content: String) {
        val invitationType: String = _topicList.value ?: "#\t其他"
        val call = _isShowCallUserNumber.value ?: ""
        viewModelScope.launch(Dispatchers.IO) {
            val userNumber =
                userNumberDao.getUserNumber(Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: "")
            val userInfo = userInfoDao.getUserInfoByUserNumber(
                Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
            )
            val maxId = invitationDao.getMaxId() ?: 0
            val invitation = InvitationTable()
            invitation.id = maxId + 1
            invitation.userNumber = Sp.getString(context, SpKey.USER_NUMBER.key, "") ?: ""
            invitation.invitationTitle = title
            invitation.invitationContent = call + "\t" + content
            invitation.invitationCreateTime = System.currentTimeMillis()
            invitation.invitationType = invitationType
            invitation.invitationImage = allImagePath
            invitation.userInfoTable = userInfo
            InvitationTable.insertWithId(invitationDao, invitation, invitation.userNumber)
            if (invitationType.contains("二手交易")) {
                schoolInfo.shoppingInvitationList.add(invitation)
                schoolInfoDao.updateSchoolInfo(schoolInfo)
            } else {
                schoolInfo.mainInvitationList.add(invitation)
                schoolInfoDao.updateSchoolInfo(schoolInfo)
            }
            if (schoolInfo?.messageList == null || schoolInfo?.messageList?.size == 0) {
                schoolInfo.messageList = mutableListOf()
                schoolInfoDao.updateSchoolInfo(schoolInfo)
            }
            userNumber?.publishList?.add(invitation)
            userNumberDao.updateUserNumber(userNumber ?: return@launch)
            if (call.isNotEmpty()) {
                val messageInfo = MessageTable()
                messageInfo.handNumber = call.replace("@:", "")
                messageInfo.sendNumber =
                    Sp.getString(context ?: return@launch, SpKey.USER_NUMBER.key ?: "", "")!!
                messageInfo.messageType = MessageTypeEnum.CALL_YOUR.value
                messageInfo.messageTime = System.currentTimeMillis()
                messageInfo.messageContent = "对方在信息内@你了，请查看"
//                messageInfo.messageContent = invitation.invitationTitle
                messageInfo.messageImage = invitation.invitationImage[0]
//                messageInfo.messageType = "对方在信息内@你了，请查看"
                messageInfo.invitationId = invitationDao.getMaxId() ?: 0
                MessageTable.insertWithId(messageDao, messageInfo)
                schoolInfo.messageList.add(messageInfo)
                schoolInfoDao.updateSchoolInfo(schoolInfo)
            }

            viewModelScope.launch(Dispatchers.Main) {
                Toast.makeText(context, "发布成功", Toast.LENGTH_SHORT).show()
                finishActivity()
            }
        }
    }
}